package com.atguigu.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.order.entity.Order;
import com.atguigu.order.entity.PayLog;
import com.atguigu.order.mapper.PayLogMapper;
import com.atguigu.order.service.OrderService;
import com.atguigu.order.service.PayLogService;
import com.atguigu.order.util.HttpClient;
import com.atguigu.order.util.WXPayLogProperties;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author Y丶HS练习谷粒商城
 * @since 2022-10-09
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Resource
    private OrderService orderService;

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public Map createNative(String orderNo) {

        try {
            // 1.查询条件，找出对应订单
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Order::getOrderNo, orderNo);
            Order order = orderService.getOne(queryWrapper);
            // 2. 使用map集合封装生成二维码得参数
            Map m = new HashMap();
            //1、设置支付参数
            m.put("appid", WXPayLogProperties.APPID);
            m.put("mch_id", WXPayLogProperties.PARTNER);
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body", order.getCourseTitle());
            m.put("out_trade_no", orderNo);
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue() + "");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url",
                    WXPayLogProperties.NOTIFY_URL);
            m.put("trade_type", "NATIVE");
            // 3. 发送httpclient，传递参数xml格式，微信支付提供得固定地址
            HttpClient client = new
                    HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, WXPayLogProperties.PARTNER_KEY));
            client.setHttps(true);
            client.post();
            //4、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            Map map = new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getCourseId());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));
            map.put("code_url", resultMap.get("code_url"));
            //微信支付二维码2小时过期，可采取2小时未支付取消订单
//            redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            // 2. 使用map集合封装生成二维码得参数
            Map m = new HashMap(4);
            //1、设置支付参数
            m.put("appid", WXPayLogProperties.APPID);
            m.put("mch_id", WXPayLogProperties.PARTNER);
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            // 根据订单查询
            m.put("out_trade_no", orderNo);

            //2、设置请求
            HttpClient client = new
                    HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,
                    WXPayLogProperties.PARTNER_KEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            //6、转成Map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //7、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        // 获取支付订单号
        String orderNo = map.get("out_trade_no");
        // 1.查询条件，找出对应订单
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getOrderNo, orderNo);
        Order order = orderService.getOne(queryWrapper);

        if(order.getStatus() == 1){
            return;
        }
        order.setStatus(1);
        // 2.更新状态
        orderService.updateById(order);
        // 3.向 支付表中增加一条支付记录
        PayLog payLog = new PayLog();
        payLog.setOrderNo(orderNo);
        // 订单完成的支付时间
        payLog.setPayTime(new Date());
        // 支付类型 微信
        payLog.setPayType(1);
        // 总金额(分)
        payLog.setTotalFee(order.getTotalFee());
        // 支付状态
        payLog.setTradeState(map.get("trade_state"));
        payLog.setTransactionId(map.get("transaction_id"));
        payLog.setAttr(JSONObject.toJSONString(map));
        // 插入到支付日志表
        baseMapper.insert(payLog);
    }
}
